#include <iostream>
#include <cstdio>
#include <string>
#include <cerrno>
#include <unistd.h>
#include <fcntl.h>

void SetNonBlock(int fd)
{
    int flag = fcntl(fd, F_GETFL);
    if(flag < 0)
    {
        perror("fcntl");
        return;
    }
    fcntl(fd, F_SETFL, flag | O_NONBLOCK);
}

int main()
{
    SetNonBlock(0);
    std::string tips = "Please Enter# ";
    char buffer[1024];

    while(true)
    {
        ::write(0, tips.c_str(), tips.size());
        ssize_t n = ::read(0, buffer, sizeof(buffer) - 1);
        if(n > 0)
        {
            buffer[n] = '\0';
            std::cout << "echo# " << buffer << std::endl;
        }
        else if(n == 0)
        {
            std::cout << "读到文件结尾" << std::endl;
            break;
        }
        else
        {
            if(errno == EAGAIN || errno == EWOULDBLOCK)
            {
                std::cout << "低层数据, 没有就绪" << std::endl;
                sleep(1);
                continue;
            }
            else if(errno == EINTR)
            {
                std::cout << "被信号中断, 重新读取" << std::endl;
                sleep(1);
                continue;
            }
            else
            {
                std::cout << "读取错误" << n << ", errno: " << errno << std::endl;
                break;
            }
        }
    }

    return 0;
}